<template>
  <div data-theme="light">
    <header class="container" style="font-size: 0">
      <hgroup>
        <h1>一套表导出</h1>
        <p>选择多文件后，自动分组入库</p>
      </hgroup>
      <a-date-picker
        v-model:value="selectedTime"
        placeholder="选择日期"
        :format="'YYYYMM'"
        :value-format="'YYYYMM'"
        :show-time="false"
        picker="month"
        style="width: 30%; margin-right: 10px"
      />
      <a-button :loading="isUploading" style="width: 30%" @click="handleUpload">上传</a-button>
      <a-button :loading="isExecuting" style="width: 30%; margin-left: 10px" @click="handleExecute">立即执行</a-button>
    </header>
    <main class="container">
      <section id="console_section">
        <div class="outer-border console">
          <div class="title">
            <span>root> /ytb/data</span>
            <a-switch v-model:checked="lockScroll" class="right" />
          </div>
          <div ref="consoleRef" class="inner-border console-text" v-html="consoleContent">
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import {defHttp} from "@/utils/http/axios";

const selectedTime = ref('');
const isUploading = ref(false);
const isExecuting = ref(false);
const lockScroll = ref(false);
const consoleContent = ref('');
const consoleRef = ref();

class Console {
  static consoleHeadTemplate = `


  `;

  init() {
    consoleContent.value = Console.consoleHeadTemplate;
  }

  write(prefix: string, val: string, level: string = 'TRACE') {
    let tagStart = '';
    let tagEnd = '';

    if (level === 'TRACE') {
      tagStart = '<span class="console_trace">';
      tagEnd = '</span><br>';
    }
    if (level === 'INFO' || level === 'END') {
      tagStart = '<span class="console_info">';
      tagEnd = '</span><br>';
    }

    consoleContent.value += ` root ${prefix}>${tagStart} ${val} ${tagEnd}`;

    if (!lockScroll.value) {
      nextTick(() => {
        if (consoleRef.value) {
          consoleRef.value.scrollTop = consoleRef.value.scrollHeight;
        }
      });
    }
  }
}

const _console = new Console();

const handleUpload = () => {
  if (isUploading.value) return;

  const input = document.createElement('input');
  input.type = 'file';
  input.multiple = true;
  input.addEventListener('change', async () => {
    if (!input.files?.length) return;

    _console.init();
    const formData = new FormData();
    Array.from(input.files).forEach(file => {
      formData.append('files[]', file);
    });

    try {
      isUploading.value = true;
      // const response = await defHttp.post('/ytbdata/update', {
      //   method: 'POST',
      //   body: formData
      // });

      defHttp.uploadMyFile('/ytbdata/update',formData).then((res: any) => {
        isUploading.value = false;
        const jobId = res.data
        console.log(jobId)
        const eventSource = defHttp.streamRequest('/watch/' + jobId);

        eventSource.addEventListener("msg", function (event) {
          console.log(event.data);
          const data = JSON.parse(event.data);
          const prefix = getDate(data.timeStamp);
          _console.write(prefix, data.messageVal, data.messageAction);
        });

        eventSource.onerror = (error) => {
          console.error('EventSource failed:', error);
          eventSource.close();
          message.error('数据流连接失败');
          isUploading.value = false;
        };

        eventSource.onclose = (event) => {
          eventSource.close();
          isUploading.value = false;
        };

        const customParams = {
          time: selectedTime.value
        };
        const headers = {
          'Content-Type': 'application/json',
        };
        const executeResponse = defHttp.post({url:'/ytbdata/execute/' + jobId,params:customParams,headers:headers}, { isTransformResponse: false }).then((res) =>{
          console.log(JSON.stringify(customParams))
          isUploading.value = false;
        }).catch((error) => {
          message.error('执行任务失败');
          isUploading.value = false;
        });

      }).catch((error) => {
        message.error('上传文件失败');
        isUploading.value = false;
      });
    } catch (error) {
      message.error(error.message || '操作失败');
      isUploading.value = false;
    }
  });

  input.click();
};

const getDate = (milliseconds: number) => {
  const d = new Date(milliseconds);
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
};

onMounted(async () => {
  try {
    const response = await fetch('/ytbdata/customParams');
    if (!response.ok) throw new Error('获取配置失败');
    const showDatePicker = await response.text() === 'true';
    if (!showDatePicker) {
      selectedTime.value = '';
    }
  } catch (error) {
    console.error('获取配置失败:', error);
  }
});

const handleExecute = async () => {
  if (isExecuting.value) return;
  
  try {
    isExecuting.value = true;
    const customParams = {
      time: selectedTime.value
    };


    // 获取当前时间戳
    const currentTime = new Date().getTime();
    const eventSource = defHttp.streamRequest('/watch/' + currentTime);
    _console.init();
    eventSource.addEventListener("msg", function (event) {
      console.log(event.data);
      const data = JSON.parse(event.data);
      const prefix = getDate(data.timeStamp);
      _console.write(prefix, data.messageVal, data.messageAction);
    });

    eventSource.onerror = (error) => {
      console.error('EventSource failed:', error);
      eventSource.close();
      message.error('数据流连接失败');
      isUploading.value = false;
    };

    eventSource.onclose = (event) => {
      eventSource.close();
      isUploading.value = false;
    };
    const headers = {
      'Content-Type': 'application/json',
    };
    defHttp.post({url:'/ytbdata/ytbDataSyncConfig/executeSync/' + currentTime,params:customParams,headers:headers,timeout:-1}, { isTransformResponse: false });
  } catch (error) {
  } finally {
    isExecuting.value = false;
  }
};
</script>

<style scoped>
.outer-border .title {
  height: 3vh;
  position: absolute;
  width: 100%;
  color: #333;
}

.outer-border {
  position: relative;
  margin: 2vh 0vh 1vh 0vh;
  border: 1px solid #e8e8e8;
  padding: 5px;
  font-size: 12px;
  border-radius: 6px;
  background-color: #fff;
}

.inner-border {
  border: 1px solid #e8e8e8;
  margin: 23px 1px 1px 1px;
  font-size: 15px;
  background-color: #fafafa;
  color: #333;
}

.console {
  position: relative;
  height: 77vh;
}

.console-text {
  height: calc(73vh);
  overflow-y: auto;
  word-break: break-all;
  padding: 10px;
}

.right {
  position: absolute;
  margin-top: -.125em;
  right: 0px;
}

.console_info {
  color: #1677ff;
}

.console_trace {
  color: #333;
}

:deep(.ant-input) {
  color: #333;
}

:deep(.ant-btn) {
  color: #fff;
  background-color: #1677ff;
}
</style>
